package es.mgil.whoWantsToBeAMillonaire.dialogs;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import es.mgil.whoWantsToBeAMillonaire.R;
import es.mgil.whoWantsToBeAMillonaire.activities.Play;
import es.mgil.whoWantsToBeAMillonaire.runnables.SendScoreRunnable;
import es.mgil.whoWantsToBeAMillonaire.util.MusicManager;
import es.mgil.whoWantsToBeAMillonaire.util.PreferencesKeys;

public class WinnerDialog extends DialogFragment {
	public static final String WINNER_DIALOG_ID = "winner_dialog_id";

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		final Play play = (Play) getActivity();
		final int score = play.getAwards().get(play.getAwards().size() - 1);

		AlertDialog.Builder builder = new AlertDialog.Builder(play);
		LayoutInflater inflater = play.getLayoutInflater();
		View content = inflater.inflate(R.layout.layout_winner, null);
		TextView scoreTextView = (TextView) content
				.findViewById(R.id.dialog_winner_score);
		scoreTextView.setText(score
				+ getResources().getString(R.string.play_award_currency));
		builder.setView(content);
		builder.setPositiveButton(R.string.play_dialog_yes,
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (MusicManager.isMusicEnabled(play.preferences)
								&& play.mmWinGame.isPlaying()) {
							// if music is enabled, and music is still playing,
							// stop it
							play.mmWinGame.stopPlayer();
						}

						// save score into database
						String name = play.preferences.getString(
								PreferencesKeys.PREFERENCES_NAME, "");
						float longitude = play.preferences.getFloat(
								PreferencesKeys.PREFERENCES_LONGITUDE, 0);
						float latitude = play.preferences.getFloat(
								PreferencesKeys.PREFERENCES_LATITUDE, 0);
						String address = play.preferences.getString(
								PreferencesKeys.PREFERENCES_ADDRESS, "");

						play.dbHelper.insertLocalScore(name, longitude,
								latitude, address, score);

						// get if it's maximum local score
						boolean isMaximum = play.dbHelper.isMaximumLocal(name,
								score);
						if (isMaximum) {
							// send score to server only if is maximum local
							// score. Send it using a runnable
							new SendScoreRunnable(getActivity(), name,
									longitude, latitude, score).sendScore();
						}

						// close the activity
						play.finish();
					}
				});

		// can't press back button while showing this dialog
		setCancelable(false);
		return builder.create();
	}
}